package org.one.afternoon.quartz;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.one.afternoon.common.Result;
import org.one.afternoon.common.SimpleUtils;
import org.one.afternoon.domain.Client;
import org.one.afternoon.forest.FrontendClient;
import org.one.afternoon.service.ClientService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.Date;

@PersistJobDataAfterExecution //持久化
@DisallowConcurrentExecution //禁止并发任务
@Component
@Slf4j
public class HealthJob extends QuartzJobBean {
    @Autowired
    private FrontendClient frontendClient;
    @Autowired
    private ClientService clientService;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        LambdaUpdateWrapper<Client> lambdaUpdateWrapper;
        try {
            Thread.sleep(2000);
            HealthJob.log.info(context.getScheduler().getSchedulerInstanceId());
            HealthJob.log.info("taskName:" + context.getJobDetail().getKey().getName());
            HealthJob.log.info("time:" + new Date());
            log.info("HealthJob is running...");
            for (int i = 0; i <= context.getJobDetail().getJobDataMap().size(); i++) {
                String ip = context.getJobDetail().getJobDataMap().getString(String.valueOf(i));
                try {
                    if (!SimpleUtils.IsNotBlank(frontendClient.isHealth(ip))) {
                        continue;
                    }else if (!frontendClient.isHealth(ip).equals("OK")) {
                        lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                        lambdaUpdateWrapper.set(Client::getStatus, 0)
                                .eq(Client::getId, i+1);
                        clientService.update(lambdaUpdateWrapper);
                    } else {
                        lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                        lambdaUpdateWrapper.set(Client::getStatus, 1)
                                .eq(Client::getId, i+1);
                        clientService.update(lambdaUpdateWrapper);
                    }
                } catch (Exception e) {
                    lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapper.set(Client::getStatus, 0)
                            .set(Client::getCustomersSign,"获取签名异常")
                            .eq(Client::getId, i+1);
                    clientService.update(lambdaUpdateWrapper);
                }


            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
